package service.impl;

import common.consts.Consts;
import dao.DeviceDao;
import domain.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.DeviceService;
import service.ServiceResponse;

import java.util.Date;

/**
 * Created by chen<chen@youjianghr.com> on 2015/7/18.
 *
 * @author chen<chen@youjianghr.com>
 */

@Service
public class DeviceServiceImpl extends ServiceBase implements DeviceService {

    @Autowired
    private DeviceDao deviceDao;

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse registerNewDevice(final long userId, final Device device) {

        Device newDevice = deviceDao.getByUserIdAndIMEI(userId, device.getImei());
        if (newDevice != null) {
            return ServiceResponse.fail(Consts.i18nKey.DUPLICATE_DEVICE_REGISTER);
        }

        newDevice = new Device();
        newDevice.setAccountId(userId);
        newDevice.setLatestUse(new Date());

        /* fields copy */
        newDevice.setBrand(device.getBrand());
        newDevice.setImei(device.getImei());
        newDevice.setDeviceToken(device.getDeviceToken());
        newDevice.setHeight(device.getHeight());
        newDevice.setWidth(device.getWidth());
        newDevice.setModel(device.getModel());
        newDevice.setOs(device.getOs());
        newDevice.setResolution(device.getResolution());

        deviceDao.insert(newDevice);

        return ServiceResponse.success();
    }

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse deleteDevice(long userId, String deviceIMEI) {
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse updateLastUse(long userId, String deviceIMEI) {

        Device device = deviceDao.getByUserIdAndIMEI(userId, deviceIMEI);
        if (device == null) {
            return ServiceResponse.fail(Consts.i18nKey.UNKNOWN_USER_DEVICE);
        }

        deviceDao.updateLastUse(device.getId());

        return ServiceResponse.success();
    }

    public void setDeviceDao(DeviceDao deviceDao) {
        this.deviceDao = deviceDao;
    }
}
